using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.ExpressApp.DC;
using DevExpress.Persistent.Base;
using DevExpress.Xpo;
using DevExpress.Persistent.Validation;
using DevExpress.ExpressApp;
using DomainComponents.Common;

namespace DomainComponents.XCRM {
    public enum CustomerStatus {
        Inactive = 0,
        Active = 1
    }
    public enum PreferredContactMethod {
        Any = 0,
        Email = 1,
        Phone = 2,
        Fax = 3,
        Mail = 4
    }

    [DomainComponent]
    [XafDefaultProperty("Name")]
    [XafDisplayName("Customer")]
    public interface ICustomer {
        [PersistentDc]
        string Name { get; }
        
        IDCUser Owner { get; set; }
        
        [System.ComponentModel.DefaultValue(CustomerStatus.Active)]
        CustomerStatus Status { get; set; }
        
        PreferredContactMethod PreferredContactMethod { get; set; }

        [VisibleInListView(false)]
        decimal CreditLimit { get; set; }

        [VisibleInListView(false)]
        bool CreditHold { get; set; }

        [Calculated("Invoices[Status == 'Completed'].Sum(Amount)")]
        decimal SaleAmount { get; }

        [Action(PredefinedCategory.View, Caption = "Activate...", AutoCommit = true,
            ConfirmationMessage = "This operation will set the selected object as Active.", TargetObjectsCriteria = "Status != 'Active'",
            SelectionDependencyType = MethodActionSelectionDependencyType.RequireMultipleObjects)]
        void Activate();
        
        [Action(PredefinedCategory.View, Caption = "Deactivate...", AutoCommit = true,
            ConfirmationMessage = CustomerLogic.DeactivateConfirmationMessage, TargetObjectsCriteria = "Status = 'Active'",
            SelectionDependencyType = MethodActionSelectionDependencyType.RequireMultipleObjects)]
        void Deactivate();
        
        [BackReferenceProperty("BackRefCustomer")]
        IList<IInvoice> Invoices { get; }
    }

    [DomainLogic(typeof(ICustomer))]
    public class CustomerLogic {
        public const string DeactivateConfirmationMessage =
@"This action will set the object as inactive. There may be records in the system that continue to reference these inactive records.

Do you want to proceed?";

        public static void Deactivate(ICustomer customer)
        {
            customer.Status = CustomerStatus.Inactive;
        }
        public static void Activate(ICustomer customer) {
            customer.Status = CustomerStatus.Active;
        }
        //public static IList<IInvoice> Get_Invoices(ICustomer customer, IObjectSpace os) {
        //    return new FilteredList<ISaleBase, IInvoice>(customer.Sales);
        //}
        //public static string Get_DisplayName(ICustomer customer) {
        //    return customer.Name;
        //}
    }
 }
